GBML manual / Maths

average

The number halfway between a and b - average(4, 10) is 7. Give it as many numbers as you like, two or more: average(2, 4, 9) is 5.

Works differently on Game Boy - average works in steps of 1/32 on the Game Boy: when the numbers add up to an odd number of steps, half a step is cut toward zero, a little coarser than on the Advance.

Works differently on Game Boy Color - average works in steps of 1/32 on the Game Boy Color: when the numbers add up to an odd number of steps, half a step is cut toward zero, a little coarser than on the Advance.

On other consoles this differs: see Side by side and How the consoles differ.

Syntax

average(a, b, ...more) -> real

Arguments

NameType
areal
breal
...morereal (any number of them, none included)

Returns

real

Description

The number halfway between a and b. average(4, 10) is 7, and average(-4, 10) is 3. It takes two or more numbers: average(2, 4, 9) is 5, the middle of all three.

Example

var mid_x = average(x, xstart);

mid_x is the spot halfway between where this object is now and where it started.

More than two numbers

Give average as many numbers as you like, two or more, in one call:

var mid = average(x, xstart, 100);

Every number counts once. average(average(a, b), c) is not the average of three. It gives c half of the weight instead of a third, and a and b a quarter each - so give all three to the one call, average(a, b, c).

It does not overflow

Writing (a + b) / 2 by hand adds first, and the sum of two big numbers can pass the top of a real (about 524,288) even when each of them is fine. average does the sum in a bigger box, so average(500000, 500000) is 500000 and average(-500000, -500000) is -500000.

One step of rounding

A real counts in steps of 1/4096. When the two numbers add up to an odd number of steps, half a step is lost, rounded toward zero. It is far too small to see on a screen, and it does not add up the way a chain of multiplies does.

Cost

A 64-bit add and a shift. Measured at about 60 cycles a call, counting the loop around it - cheap enough for every frame.

On the GBA

Never overflows: the sum is taken in 64 bits, so average(500000, 500000) is 500000, where (a + b) / 2 wraps round. An odd sum loses at most half a 1/4096 step, rounded toward zero. Every number counts once, so average(2, 4, 9) is the middle of all three - average(average(2, 4), 9) is NOT that (it weights 9 twice as much as 2 or 4).

See also: minmaxlerpNumbers